package com.tianyu.inspection.controller;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tianyu.inspection.common.Constants;
import com.tianyu.inspection.common.enums.FileTypeEnum;
import com.tianyu.inspection.common.enums.RoState;
import com.tianyu.inspection.common.annotation.Permission;
import com.tianyu.inspection.common.component.AppConstants;
import com.tianyu.inspection.common.component.Validate;
import com.tianyu.inspection.entity.ConstructionUnits;
import com.tianyu.inspection.entity.User;
import com.tianyu.inspection.entity.model.OperateMo;
import com.tianyu.inspection.entity.model.QueryMo;
import com.tianyu.inspection.entity.vo.Ro;
import com.tianyu.inspection.entity.vo.ServiceRo;
import com.tianyu.inspection.service.api.IConstructionUnitsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**********************************
 * @Author YSW
 * @Description 施工单位接口
 * @Date 2021/1/15 - 18:12
 **********************************/

@Slf4j
@RestController
@RequestMapping("/api/2.0/constructionUnits")
public class ConstructionUnitsController {

    @Resource
    private IConstructionUnitsService constructionUnitsService;

    @Resource
    private Validate validateModel;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Resource
    private AppConstants appConstants;

    @GetMapping(value = "/list")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<IPage<ConstructionUnits>> getPageList(HttpServletRequest request, @RequestHeader("u-projectId") Integer projectId,
                                                    @RequestHeader("u-uid") Integer userId){
        QueryMo queryMo = QueryMo.getQueryMo(request);
        Ro<IPage<ConstructionUnits>> ro = new Ro<>();
        int roleId = (int) request.getAttribute("roleId");
        if (roleId > 1){
            User loginUser = (User) valueOperations.get(appConstants.redisUserKey + userId);
            if (Objects.nonNull(loginUser)){
                final String constructionTypeUse = loginUser.getConstructionTypeUse();
                try {
                    final Map<String, JSONArray> modelMap = new HashMap<>(1);
                    final JSONArray jsonArray = JSONArray.parseArray(constructionTypeUse);
                    if (Objects.isNull(jsonArray) || jsonArray.size() == 0){
                        return ro.setResultEnum(RoState.FAIL).setMessage("类型未配置");
                    }else {
                        modelMap.put("construction_type_id", jsonArray);
                    }
                    queryMo.setInMap(modelMap);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }
        }
        queryMo.build(ConstructionUnits.class,projectId);
        return ro.setContent(constructionUnitsService.searchListPage(queryMo));
    }

    @GetMapping(value = "/{id}")
    @Permission(value = 4,tags = Constants.API_PATROL)
    public Ro<ConstructionUnits> getOne(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<ConstructionUnits> ro = new Ro<>();
        if (Objects.isNull(id)){
            return ro.setResultEnum(RoState.PARAMS_MISS_ERROR);
        }
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(ConstructionUnits.class,projectId);
        ConstructionUnits constructionUnits = constructionUnitsService.selectOne(queryMo);
        if (Objects.isNull(constructionUnits)){
            ro.setMessage("未查询到数据");
        }else {
            ro.setContent(constructionUnits);
        }
        return ro;
    }

    @PostMapping(value = "/insert")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<ConstructionUnits> insert(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<ConstructionUnits> ro = new Ro<>();
        operateMo.createBuild(ConstructionUnits.class,projectId);
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        String number = (String) operateMo.getEntity().get("number");
        Object constructionTypeId = operateMo.getEntity().get("constructionTypeId");
        Integer projectId1 = (Integer)operateMo.getEntity().get("projectId");
        Object pipelineId = operateMo.getEntity().get("pipelineId");
        Object pipelineStationId = operateMo.getEntity().get("pipelineStationId");
        String sceneImage = (String)operateMo.getEntity().get("sceneImage");
        String safeAreaImage = (String)operateMo.getEntity().get("safeAreaImage");
        if (Objects.isNull(constructionTypeId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[constructionTypeId]");
        } else {
            if (validateModel.constructionTypeIdValidate(Integer.parseInt(constructionTypeId.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[constructionTypeId],值不存在");
            }
        }
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(number)){
            final ConstructionUnits constructionUnits = validateModel.constructionUnitsNumberValidate(number, projectId1);
            if (Objects.nonNull(constructionUnits)){
                if(constructionUnits.getState().equals(0)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                }else {
                    delete(constructionUnits.getId(),projectId1);
                }
            }
        }
        if (Objects.nonNull(pipelineId)) {
            if (validateModel.pipelineIdValidate(Integer.parseInt(pipelineId.toString()),Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineStationId)){
            if (validateModel.pipelineStationIdValidate(Integer.parseInt(pipelineStationId.toString()),Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineStationId],值不存在");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_CONSTRUCTION_UNITS_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (Objects.nonNull(safeAreaImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_CONSTRUCTION_UNITS_IMG.getValue(),safeAreaImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[safeAreaImage],文件不存在或文件上传类别错误");
            }
        }
        if (!constructionUnitsService.insert(operateMo)){
            ro.setResultEnum(RoState.FAIL);
        }
        return ro;
    }

    @PatchMapping(value = "/modify")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<ConstructionUnits> modify(@RequestBody OperateMo operateMo, @RequestHeader("u-projectId") Integer projectId){
        Ro<ConstructionUnits> ro = new Ro<>();
        final ServiceRo serviceRo = operateMo.updateBuild(ConstructionUnits.class, projectId);
        if (!serviceRo.getResult()){
            return ro.setResultEnum(RoState.FAIL).setMessage(serviceRo.getMessage());
        }
        if (operateMo.getEntity().size()==0){
            return ro.setResultEnum(RoState.FAIL).setMessage("无操作参数传入,请传参后重试");
        }
        if (Objects.isNull(operateMo.get("id"))){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少[id]字段,请传参后重试");
        }
        Integer id = (Integer) operateMo.get("id");
        String number = (String) operateMo.getEntity().get("number");
        Object constructionTypeId = operateMo.getEntity().get("constructionTypeId");
        Integer projectId1 = (Integer) operateMo.getEqMap().get("project_id");
        Object pipelineId = operateMo.getEntity().get("pipelineId");
        Object pipelineStationId = operateMo.getEntity().get("pipelineStationId");
        String sceneImage = (String)operateMo.getEntity().get("sceneImage");
        String safeAreaImage = (String)operateMo.getEntity().get("safeAreaImage");
        if (Objects.isNull(constructionTypeId)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[constructionTypeId]");
        } else {
            if (validateModel.constructionTypeIdValidate(Integer.parseInt(constructionTypeId.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[constructionTypeId],值不存在");
            }
        }
        if (Objects.isNull(projectId1)){
            return ro.setResultEnum(RoState.FAIL).setMessage("缺少参数[projectId]");
        } else {
            if (validateModel.projectIdValidate(Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[projectId],值不存在");
            }
        }
        if (Objects.nonNull(number)) {
            final ConstructionUnits constructionUnits = validateModel.constructionUnitsNumberValidate(number, projectId1);
            if (Objects.nonNull(constructionUnits) && (!constructionUnits.getId().equals(id))){
                if(constructionUnits.getState().equals(0)){
                    return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[number],值已存在");
                }else {
                    delete(constructionUnits.getId(),projectId1);
                }
            }
        }
        if (Objects.nonNull(pipelineId)){
            if (validateModel.pipelineIdValidate(Integer.parseInt(pipelineId.toString()),Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineId],值不存在");
            }
        }
        if (Objects.nonNull(pipelineStationId)){
            if (validateModel.pipelineStationIdValidate(Integer.parseInt(pipelineStationId.toString()),Integer.parseInt(projectId1.toString()))){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[pipelineStationId],值不存在");
            }
        }
        if (Objects.nonNull(sceneImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_CONSTRUCTION_UNITS_IMG.getValue(),sceneImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[sceneImage],文件不存在或文件上传类别错误");
            }
        }
        if (Objects.nonNull(safeAreaImage)){
            if (validateModel.uploadImageValidate(FileTypeEnum.FILE_CONSTRUCTION_UNITS_IMG.getValue(),safeAreaImage)){
                return ro.setResultEnum(RoState.FAIL).setMessage("参数错误[safeAreaImage],文件不存在或文件上传类别错误");
            }
        }
        if (!constructionUnitsService.update(operateMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("参数无匹配,修改失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/{id}")
    @Permission(value = 1,tags = Constants.API_SUPER)
    public Ro<ConstructionUnits> delete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<ConstructionUnits> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(ConstructionUnits.class,projectId);
        queryMo.getEqMap().remove("state");
        if (!constructionUnitsService.delete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }

    @DeleteMapping(value = "/delete/logical/{id}")
    @Permission(value = 2,tags = Constants.API_ADMIN)
    public Ro<ConstructionUnits>  logicallyDelete(@PathVariable Integer id, @RequestHeader("u-projectId") Integer projectId){
        Ro<ConstructionUnits> ro = new Ro<>();
        QueryMo queryMo = new QueryMo();
        queryMo.put("id",id);
        queryMo.build(ConstructionUnits.class,projectId);
        if (!constructionUnitsService.logicallyDelete(queryMo)){
            ro.setResultEnum(RoState.FAIL).setMessage("无匹配ID,删除失败");
        }
        return ro;
    }
}
